import {defineStore} from "pinia";
import {ref} from "vue";

export const useSearchHistoryStore = defineStore('searchHistory', () => {
        const searchHistory = ref<string[]|undefined>()

        /**
         * 添加搜索历史
         * @param keyword 搜索历史
         */
        const updateSearchHistory = (keyword: string) => {
            // 当前关键字是否已经存在于历史记录中
            //1、存在——将其顺序提前到第一位
            // 2、不存在——直接添加到数组头部
            if (!searchHistory.value){
             return searchHistory.value=[keyword]
            }
            searchHistory.value= searchHistory.value.filter((item) => item !== keyword);
            searchHistory.value.unshift(keyword)
        }
        const clearSearchHistory = () => {
            searchHistory.value = undefined
        }
        return {
            searchHistory,
            updateSearchHistory,
            clearSearchHistory
        }
    },
    {
        persist: {
            storage: {
                setItem(key, value) {
                    uni.setStorageSync(key, value)
                },
                getItem(key) {
                    return uni.getStorageSync(key)
                },
            },
        },
    }
)